package com.taskschecker;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.taskschecker.db.DBManager;
import com.taskschecker.db.TaskGroup;
import com.taskschecker.db.TaskInfo;

public class TaskGroupAddActivity extends Activity {
	private DBManager mgr;
	private EditText startDate;
	private EditText endDate;
	private EditText contentText;
	private EditText memoText;
	private Button btnSave;
	private RadioGroup repeatGroup;
	private LinearLayout weekLayout;
	private LinearLayout monthLayout;
	private RadioButton radio1;
	private RadioButton radio2;
	private RadioButton radio3;
	private int mYear;
	private int mMonth;
	private int mDay;
	private int timeFlag;
	private ArrayList<CheckBox> weekList = new ArrayList<CheckBox>();
	private ArrayList<CheckBox> dayList = new ArrayList<CheckBox>();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_task_group_add);

		mgr = new DBManager(this);

		DisplayMetrics metric = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metric);
		int screenWidth = metric.widthPixels;
		LinearLayout.LayoutParams layout_params = new LinearLayout.LayoutParams(
				ViewGroup.LayoutParams.WRAP_CONTENT,
				ViewGroup.LayoutParams.WRAP_CONTENT);
		layout_params.width = screenWidth / 2 - 20;

		startDate = (EditText) findViewById(R.id.EditText_StartDate);
		startDate.setLayoutParams(layout_params);
		startDate.setText(CalendarUtils.getCurrentDateStr());
		startDate.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				timeFlag = 0;
				mYear = Integer.parseInt(startDate.getText().toString()
						.split("-")[0]);
				mMonth = Integer.parseInt(startDate.getText().toString()
						.split("-")[1]) - 1;
				mDay = Integer.parseInt(startDate.getText().toString()
						.split("-")[2]);
				showDialog(0);
			}
		});
		startDate.setOnFocusChangeListener(new OnFocusChangeListener() {
			public void onFocusChange(View v, boolean hasFocus) {
				if (hasFocus == true) {
					timeFlag = 0;
					mYear = Integer.parseInt(startDate.getText().toString()
							.split("-")[0]);
					mMonth = Integer.parseInt(startDate.getText().toString()
							.split("-")[1]) - 1;
					mDay = Integer.parseInt(startDate.getText().toString()
							.split("-")[2]);
					showDialog(0);
				}
			}
		});

		endDate = (EditText) findViewById(R.id.EditText_EndDate);
		endDate.setLayoutParams(layout_params);
		endDate.setText(CalendarUtils.getCurrentDateStr());
		endDate.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				timeFlag = 1;
				mYear = Integer.parseInt(endDate.getText().toString()
						.split("-")[0]);
				mMonth = Integer.parseInt(endDate.getText().toString()
						.split("-")[1]) - 1;
				mDay = Integer
						.parseInt(endDate.getText().toString().split("-")[2]);
				showDialog(1);
			}
		});
		endDate.setOnFocusChangeListener(new OnFocusChangeListener() {
			public void onFocusChange(View v, boolean hasFocus) {
				if (hasFocus == true) {
					timeFlag = 1;
					mYear = Integer.parseInt(endDate.getText().toString()
							.split("-")[0]);
					mMonth = Integer.parseInt(endDate.getText().toString()
							.split("-")[1]) - 1;
					mDay = Integer.parseInt(endDate.getText().toString()
							.split("-")[2]);
					showDialog(1);
				}
			}
		});

		contentText = (EditText) findViewById(R.id.EditText_Content);
		memoText = (EditText) findViewById(R.id.EditText_Memo);
		btnSave = (Button) findViewById(R.id.Button_AddSave);
		repeatGroup = (RadioGroup) findViewById(R.id.repeatGroup);
		weekLayout = (LinearLayout) findViewById(R.id.weekLayout);
		monthLayout = (LinearLayout) findViewById(R.id.monthLayout);
		radio1 = (RadioButton) findViewById(R.id.ataaw1);
		radio2 = (RadioButton) findViewById(R.id.ataaw2);
		radio3 = (RadioButton) findViewById(R.id.ataaw3);

		mYear = CalendarUtils.getCurrentDateSplit().get("YEAR");
		mMonth = CalendarUtils.getCurrentDateSplit().get("MONTH");
		mDay = CalendarUtils.getCurrentDateSplit().get("DAY");

		btnSave.setOnClickListener(new OnClickListener() {
			@SuppressLint("SimpleDateFormat")
			public void onClick(View v) {

				if (checkData(
						contentText.getText().toString(),
						Integer.valueOf(startDate.getText().toString()
								.replace("-", "")),
						Integer.valueOf(endDate.getText().toString()
								.replace("-", "")))) {
					TaskGroup taskgroup = new TaskGroup();
					ArrayList<TaskInfo> taskinfos = new ArrayList<TaskInfo>();
					taskgroup.setContent(contentText.getText().toString());
					taskgroup.setStartdate(Integer.valueOf(startDate.getText()
							.toString().replace("-", "")));
					taskgroup.setEnddate(Integer.valueOf(endDate.getText()
							.toString().replace("-", "")));
					taskgroup.setMemo(memoText.getText().toString());
					List<String> dateStr = getDateStrOfDayRepeat(startDate
							.getText().toString(), endDate.getText().toString());
					SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");

					if (repeatGroup.getCheckedRadioButtonId() == radio1.getId()) {
						taskgroup.setRepeatetype(0);
						taskgroup.setRepeatevalue("");
						for (String tempDate : dateStr) {
							TaskInfo taskinfo = new TaskInfo();

							taskinfo.setContent(taskgroup.getContent());
							taskinfo.setDate(Integer.valueOf(tempDate.replace(
									"-", "")));
							taskinfo.setMemo(taskgroup.getMemo());
							taskinfo.setCompleteness(0);
							taskinfo.setGroupid(0);
							taskinfos.add(taskinfo);
						}
					} else if (repeatGroup.getCheckedRadioButtonId() == radio2
							.getId()) {
						taskgroup.setRepeatetype(1);
						String weekStr = "";
						creatWeekList();
						int i = 1;
						for (CheckBox cb : weekList) {
							if (cb.isChecked()) {
								if (weekStr.equals("")) {
									weekStr = Integer.toString(i);
								} else {
									weekStr += "," + Integer.toString(i);
								}
							}
							i++;
						}
						taskgroup.setRepeatevalue(weekStr);
						Calendar tempCalendar = new GregorianCalendar();
						Date tempDay = null;
						for (String tempDate : dateStr) {
							try {
								tempDay = df.parse(tempDate);
							} catch (ParseException e) {
								e.printStackTrace();
							}
							tempCalendar.setTime(tempDay);
							int dayOfWeek = tempCalendar
									.get(Calendar.DAY_OF_WEEK);
							if (weekStr.indexOf(Integer.toString(dayOfWeek)) > -1) {
								TaskInfo taskinfo = new TaskInfo();
								taskinfo.setContent(taskgroup.getContent());
								taskinfo.setDate(Integer.valueOf(tempDate
										.replace("-", "")));
								taskinfo.setMemo(taskgroup.getMemo());
								taskinfo.setCompleteness(0);
								taskinfo.setGroupid(0);
								taskinfos.add(taskinfo);
							}
						}
					} else if (repeatGroup.getCheckedRadioButtonId() == radio3
							.getId()) {
						taskgroup.setRepeatetype(2);
						String dayStr = "";
						creatDayList();
						int i = 1;
						for (CheckBox cb : dayList) {
							if (cb.isChecked()) {
								if (dayStr.equals("")) {
									dayStr = Integer.toString(i);
								} else {
									dayStr += "," + Integer.toString(i);
								}
							}
							i++;
						}
						taskgroup.setRepeatevalue(dayStr);

						Calendar tempCalendar = new GregorianCalendar();
						Date tempDay = null;
						for (String tempDate : dateStr) {
							try {
								tempDay = df.parse(tempDate);
							} catch (ParseException e) {
								e.printStackTrace();
							}
							tempCalendar.setTime(tempDay);
							int dayOfMonth = tempCalendar
									.get(Calendar.DAY_OF_MONTH);
							if (("," + dayStr + ",").indexOf((","
									+ Integer.toString(dayOfMonth) + ",")) > -1) {
								TaskInfo taskinfo = new TaskInfo();
								taskinfo.setContent(taskgroup.getContent());
								taskinfo.setDate(Integer.valueOf(tempDate
										.replace("-", "")));
								taskinfo.setMemo(taskgroup.getMemo());
								taskinfo.setCompleteness(0);
								taskinfo.setGroupid(0);
								taskinfos.add(taskinfo);
							}
						}
					}
					mgr.addTaskGroupAndTaskInfo(taskgroup, taskinfos);
					sendUpdateWidgetBroadcast();
					finish();

				}

			}
		});

		repeatGroup
				.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
					@Override
					public void onCheckedChanged(RadioGroup group, int checkedId) {
						if (checkedId == radio1.getId()) {
							weekLayout.setVisibility(View.GONE);
							monthLayout.setVisibility(View.GONE);
						} else if (checkedId == radio2.getId()) {
							weekLayout.setVisibility(View.VISIBLE);
							monthLayout.setVisibility(View.GONE);
						} else if (checkedId == radio3.getId()) {
							weekLayout.setVisibility(View.GONE);
							monthLayout.setVisibility(View.VISIBLE);
						}
					}
				});

	}

	private boolean checkData(String content, Integer startDate, Integer endDate) {
		if ("".equals(content)) {
			AlertDialog.Builder builder = new AlertDialog.Builder(
					TaskGroupAddActivity.this);
			builder.setMessage(getResources().getString(
					R.string.message_check_content));
			builder.setPositiveButton("OK", null);
			builder.show();
			return false;
		} else if (startDate > endDate) {
			AlertDialog.Builder builder = new AlertDialog.Builder(
					TaskGroupAddActivity.this);
			builder.setMessage(getResources().getString(
					R.string.message_check_date));
			builder.setPositiveButton("OK", null);
			builder.show();
			return false;
		} else {
			return true;
		}
	}

	@SuppressLint("SimpleDateFormat")
	private List<String> getDateStrOfDayRepeat(String startDate, String endDate) {
		List<String> dateList = new ArrayList<String>();

		Calendar calStart = new GregorianCalendar();
		Calendar calEnd = new GregorianCalendar();
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		Date dayStart = null;
		Date dayEnd = null;
		try {
			dayStart = df.parse(startDate);
			dayEnd = df.parse(endDate);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		calStart.setTime(dayStart);
		calEnd.setTime(dayEnd);
		for (; calStart.compareTo(calEnd) <= 0;) {
			dateList.add(df.format(calStart.getTime()));
			calStart.add(Calendar.DAY_OF_YEAR, 1);
		}
		return dateList;
	}

	private void creatWeekList() {
		weekList.add((CheckBox) findViewById(R.id.checkBox_week1));
		weekList.add((CheckBox) findViewById(R.id.checkBox_week2));
		weekList.add((CheckBox) findViewById(R.id.checkBox_week3));
		weekList.add((CheckBox) findViewById(R.id.checkBox_week4));
		weekList.add((CheckBox) findViewById(R.id.checkBox_week5));
		weekList.add((CheckBox) findViewById(R.id.checkBox_week6));
		weekList.add((CheckBox) findViewById(R.id.checkBox_week7));
	}

	private void creatDayList() {
		dayList.add((CheckBox) findViewById(R.id.checkBox_day1));
		dayList.add((CheckBox) findViewById(R.id.checkBox_day2));
		dayList.add((CheckBox) findViewById(R.id.checkBox_day3));
		dayList.add((CheckBox) findViewById(R.id.checkBox_day4));
		dayList.add((CheckBox) findViewById(R.id.checkBox_day5));
		dayList.add((CheckBox) findViewById(R.id.checkBox_day6));
		dayList.add((CheckBox) findViewById(R.id.checkBox_day7));
		dayList.add((CheckBox) findViewById(R.id.checkBox_day8));
		dayList.add((CheckBox) findViewById(R.id.checkBox_day9));
		dayList.add((CheckBox) findViewById(R.id.checkBox_day10));
		dayList.add((CheckBox) findViewById(R.id.checkBox_day11));
		dayList.add((CheckBox) findViewById(R.id.checkBox_day12));
		dayList.add((CheckBox) findViewById(R.id.checkBox_day13));
		dayList.add((CheckBox) findViewById(R.id.checkBox_day14));
		dayList.add((CheckBox) findViewById(R.id.checkBox_day15));
		dayList.add((CheckBox) findViewById(R.id.checkBox_day16));
		dayList.add((CheckBox) findViewById(R.id.checkBox_day17));
		dayList.add((CheckBox) findViewById(R.id.checkBox_day18));
		dayList.add((CheckBox) findViewById(R.id.checkBox_day19));
		dayList.add((CheckBox) findViewById(R.id.checkBox_day20));
		dayList.add((CheckBox) findViewById(R.id.checkBox_day21));
		dayList.add((CheckBox) findViewById(R.id.checkBox_day22));
		dayList.add((CheckBox) findViewById(R.id.checkBox_day23));
		dayList.add((CheckBox) findViewById(R.id.checkBox_day24));
		dayList.add((CheckBox) findViewById(R.id.checkBox_day25));
		dayList.add((CheckBox) findViewById(R.id.checkBox_day26));
		dayList.add((CheckBox) findViewById(R.id.checkBox_day27));
		dayList.add((CheckBox) findViewById(R.id.checkBox_day28));
		dayList.add((CheckBox) findViewById(R.id.checkBox_day29));
		dayList.add((CheckBox) findViewById(R.id.checkBox_day30));
		dayList.add((CheckBox) findViewById(R.id.checkBox_day31));
	}

	private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			String mm;
			String dd;
			if (monthOfYear < 9) {
				mm = "0" + (monthOfYear + 1);
			} else {
				mm = String.valueOf(monthOfYear + 1);
			}
			if (dayOfMonth <= 9) {
				dd = "0" + dayOfMonth;
			} else {
				dd = String.valueOf(dayOfMonth);
			}
			if (timeFlag == 0) {
				startDate.setText(String.valueOf(year) + "-" + mm + "-" + dd);
			} else {
				endDate.setText(String.valueOf(year) + "-" + mm + "-" + dd);
			}
		}
	};

	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case 0:
			return new DatePickerDialog(this, mDateSetListener, mYear, mMonth,
					mDay);
		case 1:
			return new DatePickerDialog(this, mDateSetListener, mYear, mMonth,
					mDay);
		}
		return null;
	}

	public void sendUpdateWidgetBroadcast() {
		Intent intent = new Intent();
		intent.setAction("cmn.taskschecker.widget.update");
		getApplicationContext().sendBroadcast(intent);
	}
}
